<?php
// +----------------------------------------------------------------------
// |商品控制器
// +----------------------------------------------------------------------
// |Data:2016-06-28 上午10:46
// +----------------------------------------------------------------------
// |Author: 吕志雄 <870923001@qq.com>
// +----------------------------------------------------------------------
namespace Wap\Controller;
use Common\Controller\CommonController;

class ProductController extends CommonController{
    private $_model;
    private $redis_car_key = '';
    protected $redis;
    protected function _initialize(){
        parent::_initialize();
        $this->_model = D('Wap/Product');
        $this->redis_car_key = 'sp_shopping_car_'.$this->uid;
    }

    /**
     * 列表
     */
    public function index(){
        $map = $this->search();
        $res = S($this->redis_car_key.'_'.$map['shop_id']);
        $newArr = unserialize($res);
        $data = $this->_model->getList($map);
        foreach($data['cateList'] as &$val){
            $num = 0;
            foreach($newArr[$map['shop_id']] as $v){
                if($val['id'] == $v['cate_id']){
                    $num = $num+$v['num'];
                }
            }
            $val['tipNum'] = $num;
        }
        $detail = D('Common/Shop')->detail($map['shop_id']);
        $this->assign('detail',$detail);
        $this->assign('cateList',$data['cateList']);
        $this->assign('productList',$data['productList']);
        $this->assign('data',$newArr[$map['shop_id']]);
        $totalData = $this->getPrice($map['shop_id'],$newArr);
        $this->assign('totalData',$totalData);
        $this->display();
    }

    /**
     * 搜索
     */
    public function searchs(){
        $keyword = I('get.keyword','','trim');
        $shop_id = I('get.id');
        if(empty($shop_id)){
            redirect('/Index/index');
        }

        $this->assign('shop_id',$shop_id);
        $map = array();
        $map['shop_id'] = $shop_id;
        if($keyword){
            $keyword = urldecode($keyword);
            $map['title'] = array('like','%'.$keyword.'%');
        }else{
            $this->display();
            return;
        }

        $res = S($this->redis_car_key.'_'.$map['shop_id']);
        $newArr = unserialize($res);
        $data = $this->_model->getSearchList($map);
        foreach($data as &$val){
            $num = 0;
            foreach($newArr[$map['shop_id']] as $v){
                if($val['id'] == $v['cate_id']){
                    $num = $num+$v['num'];
                }
            }
            $val['tipNum'] = $num;
        }
        $detail = D('Common/Shop')->detail($map['shop_id']);
        $this->assign('detail',$detail);
        $this->assign('productList',$data);
        $this->assign('data',$newArr[$map['shop_id']]);
        $totalData = $this->getPrice($map['shop_id'],$newArr);
        $this->assign('totalData',$totalData);
        $this->assign('keyword',$keyword);
        $this->display();
    }

    /**
     * 构造查询条件
     * @return array|bool
     */
    private function search(){
        $keyword = I('get.keyword','','trim');
        $shop_id = I('get.id');
        if(empty($shop_id)){
            redirect('/Index/index');
        }

        $map = array();
        $map['shop_id'] = $shop_id;
        if($keyword){
            $keyword = urldecode($keyword);
            $map['title'] = array('like','%'.$keyword.'%');
        }

        $this->assign('keyword',$keyword);
        $this->assign('shop_id',$shop_id);
        return $map;
    }

    /**
     * 获取属性
     */
    public function getAttr(){
        $id = I('get.id');
        $num = I('get.num',1);
        $shop_id = I('get.sid');
        empty($id) || empty($shop_id) && $this->returnData('请选择操作项!');

        $detail = D('Admin/Product')->detail($id);
        if($detail['attr']){
            $res = S($this->redis_car_key.'_'.$shop_id);
            $newArr = unserialize($res);
            if($newArr){
                $keyArr = array_keys($newArr[$shop_id]);
                arsort($keyArr);
                $key = current($keyArr);
                if($key == 0){
                    $tag = 1;
                }else{
                    $tag = current($keyArr) + 1;
                }
            }else{
                $tag = 0;
            }
            $data = unserialize($detail['attr']);
            $html = '<div class="item">';
            $html .='<p class="tit">第<em>'.$num.'</em>份，价格：<b class="price">￥<em class="unit_fprice">'.$data[0]['price'].'</em></b></p>';
            $html .='<div class="format cf"><span class="fot">大小：</span>';
            $index = 1;
            foreach($data as $key=>$val){
                if($index == 1){
                    $class = 'class="active"';
                }else{
                    $class = '';
                }
                $html .= '<a href="javascript:;" '.$class.' data-tag="'.($tag).'" data-key="'.$val['key'].'" data-price="'.$val['price'].'" data-cid="'.$detail['cate_id'].'" data-id="'.$id.'">'.$val['name'].'</a>';
                $index++;
            }
            $html .='</div></div>';
            $this->returnData('',1,$html);
        }else{
            $this->returnData('',2);
        }
    }

    /**
     * 增加
     */
    public function add(){
        $product_id = I('post.id');//商品ID
        $cid = I('post.cid');//分类ID
        $attr = I('post.attr');//属性key
        $shop_id = I('post.sid');//店铺ID

        empty($product_id) && $this->returnData('请选择商品!');
        empty($cid) && $this->returnData('请选择分类ID!');
        empty($shop_id) && $this->returnData('请选择对应的分店!');

        $res = S($this->redis_car_key.'_'.$shop_id);
        $newArr = unserialize($res);

        $shopIdArr = array();
        foreach($newArr as $key=>$val){
            array_push($shopIdArr,$key);
        }

        if(empty($newArr) || !in_array($shop_id,$shopIdArr)){
            $newArr[$shop_id][] = array(
                'product_id'=>$product_id,
                'attr_key'=>$attr,
                'cate_id'=>$cid,
                'num'=>1
            );
        }else{
            $arr = array(
                'product_id'=>$product_id,
                'attr_key'=>$attr,
                'cate_id'=>$cid,
                'num'=>1
            );
            array_push($newArr[$shop_id],$arr);
        }
        S($this->redis_car_key.'_'.$shop_id,serialize($newArr));
        $data = $this->getPrice($shop_id,$newArr);
        $keyArr = array();
        foreach($newArr[$shop_id] as $key=>$val){
            array_push($keyArr,$key);
        }
        $newKeyArr = array_values($keyArr);
        $data['tag'] = end($newKeyArr);
        $this->returnData('添加成功!',1,$data);
    }

    /**
     * 修改(同一个商品,修改规格)
     */
    public function update(){
        $product_id = I('post.id');//商品ID
        $cid = I('post.cid');//分类ID
        $attr = I('post.attr');//属性key
        $shop_id = I('post.sid');//店铺ID
        $tag = I('post.tag',0);//数组索引

        empty($product_id) && $this->returnData('请选择商品!');
        empty($cid) && $this->returnData('请选择分类ID!');
        empty($attr) && $this->returnData('请选择规格!');
        empty($shop_id) && $this->returnData('请选择对应的分店!');

        $res = S($this->redis_car_key.'_'.$shop_id);
        $newArr = unserialize($res);
        if(empty($newArr)) $this->returnData('数据不存在！',1);
        $newArr[$shop_id][$tag]['attr_key'] = $attr;

        S($this->redis_car_key.'_'.$shop_id,serialize($newArr));
        $data = $this->getPrice($shop_id,$newArr);
        $this->returnData('修改成功!',1,$data);
    }

    /**
     * 删除(商品)
     */
    public function del(){
        $product_id = I('post.id');//商品ID
        $cid = I('post.cid');//分类ID
        $shop_id = I('post.sid');//店铺ID
        $tag = I('post.tag',0);//多个用逗号分隔
        if($tag){
            $tagArr = is_array($tag) ? $tag : str2arr($tag);//1,2,3
            $tag = $tagArr[0];
        }

        empty($product_id) && $this->returnData('请选择商品!');
        empty($cid) && $this->returnData('请选择分类ID!');
        empty($shop_id) && $this->returnData('请选择对应的分店!');

        $res = S($this->redis_car_key.'_'.$shop_id);
        $newArr = unserialize($res);
        unset($newArr[$shop_id][$tag]);

        S($this->redis_car_key.'_'.$shop_id,serialize($newArr));
        $data = $this->getPrice($shop_id,$newArr);
        if($tag){
            $newArr = array_diff_assoc($tagArr,array($tag));
            $data['tag'] = arr2str($newArr);
        }else{
            $data['tag'] = 0;
        }
        $this->returnData('删除成功',1,$data);
    }

    /**
     * 获取价格
     */
    public function getPrice($shop_id,$newArr){
        if(empty($shop_id)) $this->returnData('数据不合法!');
        $priceArr = array();
        $numArr = array();
        foreach($newArr[$shop_id] as $val){
            array_push($numArr,$val['num']);
            $detail = D('Admin/Product')->detail($val['product_id']);
            if($val['attr_key']){
                $attrArr = unserialize($detail['attr']);
                foreach($attrArr as $v){
                    if($v['key'] == $val['attr_key']){
                        $price = $v['price'] * $val['num'];
                        array_push($priceArr,$price);
                    }
                }
            }else{
                $price = $detail['price'] * $val['num'];
                array_push($priceArr,$price);
            }
        }

        $total = array_sum($priceArr);
        $num = array_sum($numArr);
        $data = array('price'=>$total,'num'=>$num);
        return $data;
    }

    /**
     * 购物车页面
     */
    public function cart(){
        $shop_id = I('get.id');
        if(empty($shop_id)){
            redirect('/Index/index');
        }

        $address = D('Wap/Address')->getUseAddress($this->uid);
        $address_id = I('get.aid');//地址ID
        if($address_id){
            $address = D('Wap/Address')->detail($address_id);
        }

        //购买的商品
        $res = S($this->redis_car_key.'_'.$shop_id);
        $newArr = unserialize($res);
        if(empty($newArr)){
            $this->display();
            return;
        }
        $priceArr = array();
        foreach($newArr[$shop_id] as $key=>$val){
            $detail = D('Admin/Product')->detail($val['product_id']);
            $pic = showImage($detail['pic'],'product','',2)[0];
            $title = $detail['title'];
            $sales_num = $detail['sales_num'];
            if($val['attr_key']){
                $attrArr = unserialize($detail['attr']);
                foreach($attrArr as $v){
                    if($v['key'] == $val['attr_key']){
                        $price = $v['price'] * $val['num'];
                        array_push($priceArr,$price);
                        $data[$key] = array(
                            'name'=>$v['name'],
                            'unit'=>$v['unit'],
                            'price'=>$v['price'],
                            'num'=>$val['num'],
                            'title'=>$title,
                            'pic'=>$pic,
                            'sales_num'=>$sales_num,
                            'key'=>$v['key'],
                            'id'=>$detail['id'],
                            'cid'=>$detail['cate_id']
                        );
                    }
                }
            }else{
                $price = $detail['price'] * $val['num'];
                array_push($priceArr,$price);
                $data[$key] = array(
                    'unit'=>$detail['unit'],
                    'price'=>$detail['price'],
                    'num'=>$val['num'],
                    'title'=>$title,
                    'pic'=>$pic,
                    'sales_num'=>$sales_num,
                    'id'=>$detail['id'],
                    'cid'=>$detail['cate_id']
                );
            }
        }

        $shopDetail = D('Common/Shop')->detail($shop_id);
        $this->assign('shopDetail',$shopDetail);
        //根据距离计算费用
        $price = $this->distance($shop_id,$address['location']);
        $this->assign('totalPrice',array_sum($priceArr));
        $this->assign('shop_id',$shop_id);
        $this->assign('address',$address);
        $data = $this->dealData($data);
        $this->assign('data',$data);
        $this->assign('price',$price);
        $this->display();
    }

    /**
     * 数组处理
     * @param $array
     * @return array|bool
     */
    private function dealData($array){
        if(empty($array)) return false;
        $data = array();
        foreach($array as $key=>$val){
            $val['tag'] = $key;
            $flag = 2;
            if($data){
                foreach($data as $k=>$v){
                    if($val['key']){
                        if($v['key'] == $val['key']){
                            $data[$k]['num'] ++;
                            $data[$k]['tag'] = trim($v['tag'].','.$val['tag']);
                            $flag = 1;
                            break;
                        }
                    }else{
                        if($v['id'] == $val['id']){
                            $data[$k]['num'] ++;
                            $data[$k]['tag'] = trim($v['tag'].','.$val['tag']);
                            $flag = 1;
                            break;
                        }
                    }
                }
            }
            if($flag == 2){
                array_push($data,$val);
            }
        }
        return $data;
    }

    /**
     * 获取配送费
     */
    private function distance($shop_id,$location){
        empty($shop_id) && $this->returnData('请选择操作项!');
        $detail = D('Common/Shop')->detail($shop_id);
        empty($detail) && $this->returnData('该数据不存在!');

        $price = 0;
        if($detail['free_price']){
            $priceArr = unserialize($detail['free_price']);
            list($lng,$lat) = explode(',',$detail['location']);
            $distance = getDistance($location,$lat.','.$lng);
            if($distance < 1000){
                $price = $priceArr['dprice'][0];
            }else{
                $distance = number_format($distance / 1000,1);
                foreach($priceArr['dmin_km'] as $key=>$val){
                    if($val < $distance &&  $distance <=$priceArr['dmax_km'][$key]){
                        $price = $priceArr['dprice'][$key];
                    }
                }
            }
        }
        return $price;
    }

    /**
     * 结算操作
     */
    public function settlement(){
        if(IS_POST){
            $type = I('post.type');//配送类型
            $remark = I('post.remark');//备注
            $price = I('post.price');//总价格
            $shop_id = I('post.sid');//分店ID
            $address_id = I('post.aid');//地址ID
            $dprice = I('post.dprice');//配送价格

            empty($type) && $this->returnData('请选择配送类型!');
            if($remark && abslength($remark) > 100) $this->returnData('备注长度1~100个字符!');
            empty($price) && $this->returnData('价格不能为空!');
            empty($shop_id) && $this->returnData('分店不能为空!');
            empty($address_id) && $this->returnData('请选择地址!');

            $_SESSION['shop_car_'.$this->uid.'_'.$shop_id] = null;
            $data = array(
                'type'=>$type,
                'remark'=>$remark,
                'price'=>$price,
                'shop_id'=>$shop_id,
                'address_id'=>$address_id,
            );
            $data['deliver_price'] = $type == 1 ? intval($dprice) : 0;
            $_SESSION['shop_car_'.$this->uid.'_'.$shop_id] = $data;
            $this->returnData('',1);
        }else{
            $shop_id = I('get.sid');//分店ID
            $cid = I('get.cid');
            $data = $_SESSION['shop_car_'.$this->uid.'_'.$shop_id];
            if(empty($data) || empty($shop_id)) return false;
            if($cid){
                $detail = D('Common/Coupons')->detail($cid);
            }else{
                $detail = D('Common/Coupons')->getShopUserCoupons($shop_id,$this->uid,$data['price']);
            }
            $this->assign('detail',$detail);
            $this->assign('data',$data);
            $this->display();
        }
    }

    /**
     * 提交订单
     */
    public function build(){
        if(IS_POST){
            $shop_id = I('post.sid');//分店ID
            $price = I('post.price');
            $payway = I('post.payway');//支付方式 1微信支付 2货到付款
            empty($price) && $this->returnData('价格错误!');
            empty($payway) && $this->returnData('请选择支付方式!');
            if(empty($shop_id)) return false;

            $coupons_id = I('post.id');
            if($coupons_id){
                $detail = D('Common/Coupons')->detail($coupons_id);
                $cprice = $detail['denom'];
            }
            $data = $_SESSION['shop_car_'.$this->uid.'_'.$shop_id];
            if(empty($data)) $this->returnData('数据非法!');

            $res = S($this->redis_car_key.'_'.$shop_id);
            $newArr = unserialize($res);
            $payway = $payway == 1 ? 2 : 3;
            $result = D('Wap/Order')->buildOrder($newArr[$shop_id],$data,$this->uid,$price,$payway,$coupons_id,$cprice);
            if($result){
                session('shop_car_'.$this->uid.'_'.$shop_id,null);
                S($this->redis_car_key.'_'.$shop_id,null);
                $this->returnData('下单成功!',1,$result);
            }else{
                $this->returnData('下单失败!');
            }
        }else{
            $this->returnData('请求方式错误!');
        }
    }

    /**
     * 商品详情
     */
    public function detail(){
        $id = I('get.id');
        if(empty($id)) return false;
        $detail = D('Admin/Product')->detail($id);
        if($detail['attr']){
            $attrArr = unserialize($detail['attr']);
            $priceArr = array();
            foreach($attrArr as $val){
                array_push($priceArr,$val['price']);
            }
            asort($priceArr);
            $detail['price'] = $priceArr[0];
        }
        $this->assign('detail',$detail);
        $this->display();
    }

    /**
     * 地址页面
     */
    public function address(){
        $sid = I('get.sid');
        $map = array();
        $map['uid'] = $this->uid;
        $list = D('Wap/Address')->getAll($map,'add_time desc');
        $this->assign('list',$list);
        $this->assign('sid',$sid);
        $this->display();
    }

    /**
     * 优惠券
     */
    public function coupons(){
        $shop_id = I('get.sid');
        if(empty($shop_id)) return false;

        $data = $_SESSION['shop_car_'.$this->uid.'_'.$shop_id];

        $map = array();
        $map['cr.uid'] = $this->uid;
        $map['is_use'] = 2;
        $map['is_overdue'] = 2;
        $map['is_del'] = 2;
        $map['end_time'] = array('gt',time());
        $map['shop_id'] = $shop_id;
        $map['c.max_decom'] = array('lt',$data['price']);
        $list = D('Common/Coupons')->getUserRecordList($map);
        foreach($list['data'] as &$val){
            $shopDetail = D('Common/Shop')->detail($val['shop_id']);
            $val['shopTitle'] = $shopDetail['title'];
        }
        $this->assign($list);
        $this->assign('shop_id',$shop_id);
        $this->display();
    }
}
?>